package fun.easycode.webterminal.common.util;

import cn.hutool.extra.ssh.ChannelType;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import lombok.SneakyThrows;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public final class JschExecUtil {

    @SneakyThrows
    public static String exec(Session session, String command){
        ChannelExec channel = (ChannelExec )session.openChannel(ChannelType.EXEC.getValue());

        channel.setCommand(command);

        channel.connect();

        try {
            StringBuilder r = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()))) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    r.append(line).append("\n");
                }
            }
            return r.toString();
        }finally {
            channel.disconnect();
        }
    }

}
